<template>
  <div class="layout-container">
    <div class="layout-container-form" style="flex-direction: column">
      <div class="layout-container-form-search">
        <el-row style="text-align: left">
          <el-col :span="24">
            <el-form label-width="90px" :inline="true">
              <el-form-item label="姓名：">
                <el-input v-model="query.real_name" placeholder="请输入姓名" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="领取时间：">
                <el-date-picker v-model="query.user_get_date_time" type="datetimerange" prefix-icon="el-icon-date"
                  range-separator="→" value-format="YYYY-MM-DD HH-mm-ss" start-placeholder="开始日期" end-placeholder="结束日期"
                  style="width: 100%" />
              </el-form-item>
              <el-form-item label="团队编号：">
                <el-input v-model="query.team_number" placeholder="请输入团队编号" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item label="状态：">
                <el-select v-model="query.status" placeholder="请选择状态" style="width: 100%" clearable @clear="clearStatus"
                  @change="changeStatus">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="账号ID：">
                <el-input v-model="query.user_id" placeholder="请输入账号ID" style="width: 100%"
                  @keyup.enter="getTableData(true)"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="search-btn" style="margin-left: 8px" @click="resetSearch">{{
                    $t("message.common.reset")
                }}</el-button>
                <el-button type="primary" class="search-btn" @click="getTableData(true)">{{ $t("message.common.search")
                }}</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
      <div class="layout-container-opt" style="display:flex;justify-content:space-between;position:relative;">
        <el-button
          v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions && adminInfo.action_permissions.includes('3'))"
          :type="selectData.length > 0 ? 'primary' : ''" :disabled="selectData.length === 0"
          :loading="exportBatchLoading" @click="exportExcelFun">
          批量导出数据
        </el-button>
        <el-button class="search-btn" icon="el-icon-refresh-right" style="position:absolute;right:0;bottom:8px;"
          @click="getTableData(true)">{{ $t("message.common.refresh") }}</el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true" :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
        <el-table-column prop="sn" label="序号" width="80" />
        <el-table-column prop="u_team_number" label="团队编号" />
        <el-table-column prop="user_id" label="账号ID" />
        <el-table-column prop="real_name" label="姓名" />
        <el-table-column prop="phone" label="手机号" width="150">
          <template #default="scope">{{ scope.row.phone }}</template>
        </el-table-column>
        <el-table-column prop="topic_id" label="题目ID" />
        <el-table-column prop="title" label="题目名称" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <!--  0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废 -->
            <span v-if="scope.row.status === 0">未生效</span>
            <span v-if="scope.row.status === 1">已完成</span>
            <span v-if="scope.row.status === 2">已领取</span>
            <span v-if="scope.row.status === 3">指派中</span>
            <span v-if="scope.row.status === 4">返修中</span>
            <span v-if="scope.row.status === 5">闲置中</span>
            <span v-if="scope.row.status === 6">已作废</span>
            <span v-if="scope.row.status === 7">已失效</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="剩余时间">
          <template #default="scope">
            {{ scope.row.time }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.common.handle')" width="250">
          <template #default="scope">
            <!--  0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废 -->
            <span
              v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions.includes('3'))">
              <!-- 只有已完成状态可以导出 -->
              <span v-if="scope.row.status === 1">
                <el-button type="text" :loading="exportSingleLoading" @click="handleOpt(scope.row, 'export')">
                  {{ $t("message.common.export") }}
                </el-button>
                <span class="split-line">|</span>
              </span>
            </span>
            <span
              v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions.includes('2'))">
              <!-- 只有作废才能回归题库 -->
              <span v-if="scope.row.status !== 5">
                <el-button type="text" @click="handleOpt(scope.row, 'return_questions')">
                  {{ $t("message.common.return_questions") }}
                </el-button>
                <span class="split-line">|</span>
              </span>
            </span>
            <span
              v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions.includes('2'))">
              <!-- 只有已完成才能返修 -->
              <span v-if="scope.row.status === 1">
                <el-button type="text" @click="handleOpt(scope.row, 'repair')">
                  {{ $t("message.common.repair") }}
                </el-button>
                <span class="split-line">|</span>
              </span>
            </span>
            <span
              v-if="adminInfo.admin_type < 2 || (adminInfo.admin_type === 2 && adminInfo.action_permissions.includes('2'))">
              <!-- 非作废条件下都可作废 -->
              <span v-if="scope.row.status !== 6">
                <el-button type="text" @click="handleOpt(scope.row, 'invalid')">
                  {{ $t("message.common.invalid") }}
                </el-button>
                <span class="split-line">|</span>
              </span>
            </span>
            <span v-if="adminInfo.admin_type === 0">
              <el-button type="text" @click="handleOpt(scope.row, 'del')">
                {{ $t("message.common.del") }}
              </el-button>
            </span>
          </template>
        </el-table-column>
      </Table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, ref, reactive } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage, ElMessageBox } from "element-plus";
import Table from "@/components/table/index.vue";
import {
  changeTopicStatus,
  delTopic,
  exportExcel
} from "@/api/service/project.ts";
import { dateFormat, intervalTime, calculateDiffTime } from "@/utils/index.ts";
import { getTopicQuantity } from "@/api/service/user.ts";
import { useStore } from "vuex";
const store = useStore();
const adminInfo = reactive(store.state.user.adminInfo);

// 存储搜索用的数据
const query = reactive({
  real_name: '', // string
  status: undefined, // integer -1: 查所有
  team_number: '', // string
  user_get_date_time: [], // array[string]
  user_id: '', // string
});
// 状态 0 未生效 1已完成 2 已领取 3指派中 4返修中 5 闲置中 6 已作废
const statusOptions = ref([
  {
    label: '未生效',
    value: 0
  },
  {
    label: '已完成',
    value: 1
  },
  {
    label: '已领取',
    value: 2
  },
  {
    label: '指派中',
    value: 3
  },
  {
    label: '返修中',
    value: 4
  },
  {
    label: '闲置中',
    value: 5
  },
  {
    label: '已作废',
    value: 6
  },
  {
    label: '已失效',
    value: 7
  }
])
// 清空状态
const clearStatus = () => {
  query.status = undefined;
  getTableData(true);
}
// 状态change事件
const changeStatus = () => {
  if (query.status != '') {
    getTableData(true);
  }
}
// 分页参数, 供table使用
const page: Page = reactive({
  index: 1,
  size: 50,
  total: 0,
});
// 重置
const resetSearch = () => {
  query.real_name = '', // string
    query.status = undefined, // integer -1: 查所有
    query.team_number = '', // string
    query.user_get_date_time = [], // string
    query.user_id = '', // string
    getTableData(true);
}
const loading = ref(false);
const tableData = ref([]);
// 获取表格数据
// params <init> Boolean ，默认为false，用于判断是否需要初始化分页
const getTableData = (init: Boolean) => {
  loading.value = true;
  if (init) {
    page.index = 1;
  }
  let params = {
    page: page.index,
    page_size: page.size,
    real_name: query.real_name, // string
    status: query.status === undefined ? -1 : query.status, // integer -1: 查所有
    u_team_number: query.team_number, // string
    user_get_date_time: query.user_get_date_time ? query.user_get_date_time : [], // string
    user_id: query.user_id, // string
  };
  getTopicQuantity(params)
    .then((res: any) => {
      let data = res.data.list;
      data.forEach((d: any) => {
        d.loading = false;
      });

      tableData.value = data;
      page.total = Number(res.data.count);
      tableData.value.forEach(item => {
        let timestamp = Date.now();
        let finish_time = new Date(item.finish_time).getTime()
        if (finish_time - timestamp < 0) {
          item.time = '00:00:00'
        } else {
          item.time = calculateDiffTime(timestamp, finish_time)
        }
      });
      // let timestamp = Date.now();
      // setTimeout(() => {
      //   let finish_time = Date.now();
      //   let time = calculateDiffTime(timestamp,finish_time)
      //   console.log(time)
      // }, 5000);
      console.log(tableData.value)
    })
    .catch(() => {
      tableData.value = [];
      page.index = 1;
      page.total = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 勾选数据
const selectData = ref([]); // 系统id
const selectProjectIdsData = ref([]); // 项目id
const handleSelectionChange = (data: any) => {
  selectData.value = [];
  selectProjectIdsData.value = [];
  data.forEach((item: any) => {
    selectData.value.push(item.id);
    selectProjectIdsData.value.push(item.project_id);
  });
};

// 导出题目答案与表格
const exportBatchLoading = ref(false);
const exportSingleLoading = ref(false);
const exportExcelFun = () => {
  exportBatchLoading.value = true;
  exportExcelPost(selectData.value, selectProjectIdsData.value)
}
// 导出通用函数
const exportExcelPost = (topic_ids: any, project_ids: any) => {
  let data = {
    topic_ids: topic_ids, // array[interger]
    // project_ids: project_ids, // array[string]
  }
  exportExcel(data).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('导出成功');
      window.open(res.data);
    }
  }).finally(() => {
    exportBatchLoading.value = false;
    exportSingleLoading.value = false;
  })
}
// 操作
const handleOpt = (row: any, type: String) => {
  ElMessageBox.confirm(`是否确认当前操作?`, "", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 导出
      if (type === "export") {
        exportSingleLoading.value = true;
        let topic_ids = [row.id]; // array[interger]
        let project_ids = [row.project_id]; // array[string]
        exportExcelPost(topic_ids, project_ids);
      }
      // 回归题库
      if (type === "return_questions") {
        changeTopicStatusFun(row, 5)
      }
      // 返修
      if (type === "repair") {
        changeTopicStatusFun(row, 4)
      }
      // 作废
      if (type === "invalid") {
        changeTopicStatusFun(row, 6)
      }
      if (type === "del") {
        deleteFun(row.id);
      }
    })
    .catch(() => { });
};
// 回归题库,返修,作废
const changeTopicStatusFun = (row: any, status: Number) => {
  let data = {
    id: row.id,
    status: status
  }
  changeTopicStatus(data).then((res: any) => {
    if (res.code === 200) {
      let msg = ''
      if (status === 5) {
        msg = '回归题库成功！'
      }
      if (status === 4) {
        msg = '返修成功！'
      }
      if (status === 6) {
        msg = '作废成功！'
      }
      ElMessage.success(msg);
      getTableData(true);
    }
  })
}
// 删除函数
const deleteFun = (id: any) => {
  let data = {
    id,
  };
  delTopic(data)
    .then((res: any) => {
      if (res.code == 200) {
        getTableData(false);
        ElMessage.success("删除成功！");
      } else {
        ElMessage.error("删除失败！");
      }
    })
    .catch(() => false);
};
getTableData(true);
</script>

<style lang="scss" scoped>
.layout-container-form {
  position: relative;
}

.layout-container-form-search {
  width: 100%;
  display: inline-block !important;
  justify-content: flex-start !important;

  .search-btn {
    margin-right: 10px;
    ;
  }
}

.layout-container-opt {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
  margin-top: 10px;
}

.split-line {
  margin: 0 8px;
  color: #ccc;
}

.image-slot {
  width: 50px;
  height: 50px;
  background: #fafafa;
  color: #ccc;
  font-size: 12px;
  cursor: pointer;
}
</style>
